package handler

import (
	"context"

	"gitee.com/chunanyong/zorm"
	"gitee.com/workits/workits-admin/internal/app/system/entity"
	"gitee.com/workits/workits-admin/internal/app/system/model"
)

var DictHandler = new(dictHandler)

type dictHandler struct {
}

// All 获取系统所有有效字典数据
//
//	@Summary	获取系统所有有效字典数据
//	@Tags		system
//	@Produce	json
//	@Success	200	{object}	ginx.RespWrapper{data=model.DictAllRespModel}
//	@Router		/system/dict/all [post]
func (h *dictHandler) All(ctx context.Context) ([]model.DictAllRespModel, error) {
	// 构造查询条件
	finder := zorm.NewFinder()
	finder.Append("select sys_dict_data.* from sys_dict_data")
	finder.Append("join sys_dict_type on sys_dict_type.type = sys_dict_data.type")
	finder.Append("where sys_dict_type.deleted_at is null")
	finder.Append("and sys_dict_type.disabled = ?", "N")
	finder.Append("and sys_dict_data.deleted_at is null")
	finder.Append("and sys_dict_data.disabled = ?", "N")
	finder.Append("order by sys_dict_data.type, sys_dict_data.sort_by asc")
	finder.SelectTotalCount = false

	// 执行查询
	var items []entity.SysDictDataEntity
	if err := zorm.Query(ctx, finder, &items, nil); err != nil {
		return nil, err
	}

	// 构造返回值
	retMap := make(map[string][]model.DictDataModel)
	for _, item := range items {
		dictData, ok := retMap[item.Type]
		if !ok {
			dictData = make([]model.DictDataModel, 0)
		}
		dictData = append(dictData, model.DictDataModel{
			Label:     item.Label,
			Value:     item.Value,
			IsDefault: item.IsDefault,
		})
		retMap[item.Type] = dictData
	}
	rets := make([]model.DictAllRespModel, 0)
	for k, v := range retMap {
		rets = append(rets, model.DictAllRespModel{
			Type: k,
			Data: v,
		})
	}

	return rets, nil
}
